package com.briup.srms.sms.web.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import com.briup.srms.exam.bean.extend.StudentExamExtend;
import com.briup.srms.sms.bean.EmployeeEvent;
import com.briup.srms.sms.bean.Student;
import com.briup.srms.sms.service.ITestService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.briup.srms.sms.bean.extend.StudentExtend;
import com.briup.srms.sms.service.IStudentService;
import com.briup.srms.sms.vm.StudentClazzVM;
import com.briup.srms.sms.vm.StudentsDirectionVM;
import com.jacky.base.utils.CustomerException;
import com.jacky.base.utils.ExcelUtils;
import com.jacky.base.utils.IDCardUtil;
import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.jacky.base.utils.PageVM;
import com.jacky.base.utils.RegExpValidation;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: 杰普基础管理系统
 * @description: 学生控制器类
 * @author: charles
 * @create: 2020-12-27 17:22
 **/
@Api(description = "学生相关接口")
@Validated
@RestController
@RequestMapping("/student")
public class StudentController {

	@Autowired
	private IStudentService studentService;
	@Autowired
	private ITestService testService;


	@ApiOperation(value = "批量更新学生")
	@GetMapping("batchUpdateStudentEmployment")
	public Message batchUpdateStudentEmployment(){
		testService.batchUpdateStudentEmployment();
		return  MessageUtil.success("操作成功！");
	}

	@ApiOperation(value = "生成账号")
	@GetMapping("test_generator_employment")
	public Message test_generator_employment(){
		studentService.test_generator_employment();
		return  MessageUtil.success("生成成功！");
	}

	@ApiOperation(value = "重置密码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "学生编码", paramType = "query", required = true),
	})
	@GetMapping("resetPassword")
	public Message resetPassword(long id){
		studentService.resetPassword(id);
		return MessageUtil.success("重置成功！");
	}

	@ApiOperation(value = "注册档案")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "studentId", value = "学生信息", paramType = "query", required = true),
	})
	@PostMapping("register")
	public Message register(Student student){
		studentService.register(student);
		return MessageUtil.success("注册成功！");
	}

	@ApiOperation(value = "离校")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "studentId", value = "老师ID", paramType = "query", required = true),
	})
	@GetMapping("leaveBriup")
	public Message leaveBriup(Long id){
		studentService.leaveBriup(id);
		return MessageUtil.success("离校成功");
	}

    /**
     * 恢复入学
     * @param stuId 学生ID
     * @author YuYan
     * @date 2022/03/18
     */
	@GetMapping("backBriup")
	public Message backBriup(Long stuId, Long clazzId){
		studentService.backBriup(stuId, clazzId);
		return MessageUtil.success("恢复入学成功！");
	}



	@ApiOperation(value = "调班")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "studentIds", value = "学生ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "clazzId", value = "班级ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "comment", value = "谈话内容", paramType = "query", required = true)
	})
	@PostMapping("changeClazz")
	public Message changeClazz(Long[] studentIds,Long clazzId,String comment){
		// 调班
		studentService.changeClazz(studentIds,clazzId,comment);
		return MessageUtil.success("调班成功");
	}

	@ApiOperation(value = "谈话")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "employeeId", value = "老师ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "studentId", value = "学生ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "content", value = "谈话内容", paramType = "query", required = true)
	})
	@PostMapping("talk")
	public Message talk(long employeeId,long studentId,String content) {
		studentService.talk(employeeId,studentId,content);
		return MessageUtil.success("记录成功");
	}

	@ApiOperation(value = "报道")
	@PostMapping("report")
	public Message report(@NotNull long id,String dormitoryType,String dormitory) {
		studentService.report(id,dormitoryType,dormitory);
		return MessageUtil.success("操作成功!");
	}

	@ApiOperation(value = "重点关注")
	@PostMapping("attention")
	public Message attention(@NotNull long id,String type,String comment) {
		studentService.attention(id,type,comment);
		return MessageUtil.success("关注成功!");
	}

	@ApiOperation(value = "取消关注")
	@GetMapping("cancelAttention")
	public Message cancelAttention(@NotNull long id) {
		studentService.cancelAttention(id);
		return MessageUtil.success("取消成功!");
	}

	@ApiOperation(value = "根据账号获取学生信息")
	@GetMapping("findByAccountId")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "账号ID", required = true, paramType = "query"),
	})
	public Message findByAccountId(@NotNull long id) {
		Student student = studentService.findByAccountId(id);
		return MessageUtil.success(student);
	}

	@ApiOperation(value = "选人入班")
	@PostMapping("batchConfirmClazz")
	public Message batchConfirmClazz(@RequestBody StudentClazzVM scvm) {
		studentService.batchConfirmClazz(scvm);
		return MessageUtil.success("入班成功！");
	}

	@ApiOperation(value = "确认方向")
	@PostMapping("batchConfirmDirection")
	public Message batchConfirmDirection(@RequestBody StudentsDirectionVM sdvm) {
		studentService.batchConfirmDirection(sdvm);
		return MessageUtil.success("确认成功！");
	}

	@ApiOperation(value = "修改学费信息")
	@PostMapping("batchUpdateTuition")
	public Message batchUpdateTuition( Long[] ids, String tuition, String reserve) {
		studentService.batchUpdateTuition(ids,tuition,reserve);
		return MessageUtil.success("修改成功！");
	}

	@ApiOperation(value = "确认报名信息")
	@PostMapping("batchConfirmApplay")
	public Message batchConfirmApplay( Long[] ids, String tuition, String reserve) {
		studentService.batchConfirmApplay(ids,tuition,reserve);
		return MessageUtil.success("确认成功！");
	}

	@ApiOperation(value = "生成账号信息")
	@PostMapping("generatorAccount")
	public Message generatorAccount(Long[] ids) {
		studentService.generatorAccount(ids);
		return MessageUtil.success("生成账号成功！");
	}


	@ApiOperation(value = "批量删除")
	@PostMapping("batchDelete")
	public Message batchDelete( Long[] ids) {
		studentService.batchDelete(ids);
		return MessageUtil.success("删除成功！");
	}

	@ApiOperation(value = "通过id删除")
	@ApiImplicitParams(@ApiImplicitParam(name = "id", value = "主键", paramType = "query", required = true))
	@GetMapping("deleteById")
	public Message deleteById(long id) {
		studentService.deleteById(id);
		return MessageUtil.success("删除成功");
	}

	@ApiOperation(value = "保存或更新消息信息", notes = "如果参数中包含id后端认为是更新操作，如果参数中不包含id认为是插入操作")
	@PostMapping("saveOrUpdate")
	public Message saveOrUpdate(Student student) {
		studentService.saveOrUpdate(student);
		return MessageUtil.success("更新成功");
	}


	// 导入报名信息？
	@ApiOperation(value = "文件上传", notes = "上传学生数据")
	@PostMapping("upload")
	public Message upload(@RequestParam("file") MultipartFile file,
                          HttpServletRequest req,
                          @NotNull Long channelId) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<Student> students = new ArrayList<>();
		for (List<Object> props : list) {
			Student student = new Student();
			// 设置渠道
			student.setChannelId(channelId);
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				switch (i) {
				case 0:	// 学校班级
					student.setSchoolStuClazz((String)prop);
					break;
				case 1:	// 学校学号
					student.setSchoolStuNo((String)prop);
					break;
				case 2: // 学生姓名
					student.setRealname((String)prop);
					break;
				case 3: // 钉钉手机号
					student.setDdTel(prop+"");
					break;
				case 4: // 性别
					String gender = prop+"";
					String[] genders = new String[] {"男","女"};
					boolean flag = Arrays.asList(genders).contains(gender);
					if(!flag) {
						throw new CustomerException("性别录入错误：只允许录入【男 | 女】");
					}
					student.setGender(gender);
					break;
				case 5: // 身份证号
					if(!RegExpValidation.checkIdCard(prop+"")) {
						throw new CustomerException("身份证号错误【"+prop+"】");
					}
					// 设置身份证号
					student.setIdCard(prop+"");
					String birth = IDCardUtil.getBirAgeSex(student.getIdCard()).get("birthday");
					// 设置出生日期
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date date = simpleDateFormat.parse(birth);
						long ts = date.getTime();
						student.setBirth(ts);
					} catch (Exception e) {
						// 生日为当前时间
						student.setBirth(new Date().getTime());
					}

					break;
				case 6: // 家庭住址
					student.setHomeAddress(prop+"");
					break;
				case 7: // 毕业时间
					SimpleDateFormat graduation_time_date_sdf = new SimpleDateFormat("yyyy-MM-dd");
			        Date graduation_time_date = graduation_time_date_sdf.parse(prop+"");
					student.setGraduationTime(graduation_time_date.getTime());
					break;
				case 8: // 学历
					String education = prop+"";
					String[] educations = new String[] {"专科","本科","研究生","其他"};
					boolean education_flag = Arrays.asList(educations).contains(education);
					if(!education_flag) {
						throw new CustomerException("学历录入错误：只允许录入【专科 | 本科 | 研究生 | 其他】");
					}
					student.setEducation(education);
					break;
				case 9: // 专业
					student.setMajor(prop+"");
					break;
				case 10: // 英语水平
					String flp = prop+"";
					String[] flps = new String[] {"CET-4","CET-6","CET-8","无"};
					boolean flp_flag = Arrays.asList(flps).contains(flp);
					if(!flp_flag) {
						throw new CustomerException("外语水平录入错误：只允许录入【CET-4 | CET-6 | CET-8 | 无】");
					}
					student.setFlp(flp);
					break;
				case 11: // 手机号
					String telephone = prop+"";
					if(!RegExpValidation.checkMobile(telephone)) {
						throw new CustomerException("手机号格式错误【"+telephone+"】");
					}
					student.setTel(telephone);
					break;
				case 12: // qq号
					student.setQq(prop+"");
					break;
				case 13: // 监护人手机号
					String guardianTel = prop+"";
					if(!RegExpValidation.checkMobile(guardianTel)) {
						throw new CustomerException("手机号格式错误【"+guardianTel+"】");
					}
					student.setGuardianTel(guardianTel);
					break;
				case 14: // 政治面貌
					student.setPoliticsStatus(prop+"");
					break;
				case 15: // 籍贯
					student.setNativePlace(prop+"");
					break;
				default:
					break;
				}
			}
			// 杰普学号
			if(student.getSchoolStuNo()!=null) {
				student.setStuNo(channelId+"_"+student.getSchoolStuNo());
			}
			students.add(student);
		}
		// 调用业务逻辑层代码完成批量保存操作
		studentService.batchInsert(students);
		return MessageUtil.success("导入成功");
	}

	@ApiOperation(value = "分页多条件获取学生信息")
	@GetMapping("pageQuery")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
		@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
		@ApiImplicitParam(name = "status", value = "状态", paramType = "query"),
		@ApiImplicitParam(name = "channelIds", value = "渠道", paramType = "query"),
		@ApiImplicitParam(name = "stuTypes", value = "学生类型", paramType = "query"),
		@ApiImplicitParam(name = "year", value = "毕业年份", paramType = "query"),
	})
	public Message pageQuery(@NotNull int page, int pageSize,String realname,
			Long clazzId,String status,Long[] channelIds,String[] stuTypes,String year) {
        System.out.println("【————————pageQueryStudent————————】");
        System.out.println(page);
        System.out.println(pageSize);
        System.out.println(realname);
        System.out.println(clazzId);
        System.out.println(status);
        System.out.println(Arrays.toString(channelIds));
        System.out.println(Arrays.toString(stuTypes));
        System.out.println(year);
        System.out.println("【————————pageQueryStudent end————————】");
		PageVM<StudentExtend> pageVM = studentService.pageQuery(page, pageSize,realname,clazzId,status,channelIds,stuTypes,year);
		return MessageUtil.success(pageVM);
	}

	@ApiOperation(value = "下载模板（班级学生的，期望一次性导入）",produces = "application/octet-stream")
	@GetMapping("downloadClazzStudentTemplate")
	public void downloadClazzStudentTemplate(HttpServletResponse response) throws Exception {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = this.getClass().getResourceAsStream("/template/clazz_student_template.xlsx");
			outputStream = response.getOutputStream();
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("批量导入学生信息模板.xlsx", "utf-8"));
			IOUtils.copy(inputStream, outputStream);
			response.flushBuffer();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(outputStream !=null) {
				outputStream.close();
			}
		}
	}


	@ApiOperation(value = "下载模板（旧有学生的，期望一次性导入）",produces = "application/octet-stream")
	@GetMapping("downloadOldStudentTemplate")
	public void downloadOldStudentTemplate(HttpServletResponse response) throws Exception {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = this.getClass().getResourceAsStream("/template/old_student_template.xlsx");
			outputStream = response.getOutputStream();
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("批量导入学生信息模板.xlsx", "utf-8"));
			IOUtils.copy(inputStream, outputStream);
			response.flushBuffer();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(outputStream !=null) {
				outputStream.close();
			}
		}
	}

	@ApiOperation(value = "下载模板", produces = "application/octet-stream")
	@GetMapping("downloadTemplate")
	public void downloadTemplate(HttpServletResponse response) throws Exception {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = this.getClass().getResourceAsStream("/template/student_template.xlsx");
			outputStream = response.getOutputStream();
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("批量导入学生信息模板.xlsx", "utf-8"));
			IOUtils.copy(inputStream, outputStream);
			response.flushBuffer();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(outputStream !=null) {
				outputStream.close();
			}
		}
	}

	// 下载学生信息
	@ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
	@GetMapping("download")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
		@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
		@ApiImplicitParam(name = "status", value = "状态", paramType = "query"),
		@ApiImplicitParam(name = "channelIds", value = "渠道", paramType = "query"),
		@ApiImplicitParam(name = "stuTypes", value = "学生类型", paramType = "query"),
		@ApiImplicitParam(name = "year", value = "毕业年份", paramType = "query"),
	})
	public void download(HttpServletResponse response, @NotNull int page, int pageSize,String realname,Long clazzId,
			String status,Long[] channelIds,String[] stuTypes,String year) throws Exception {
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] { "校内班级","校内学号","姓名", "钉钉手机号","性别", "民族","身份证号", "出生日期", "家庭住址","大学毕业时间","学历","学校","学院","专业","外语能力","本人手机号","本人qq","监护人手机号","政治面貌","籍贯" ,"谈话记录","考试记录"};
		// 2.2 属性
		String[] fieldList = new String[] { "schoolStuClazz","schoolStuNo","realname", "ddTel","gender", "nation","idCard", "birth", "address", "graduationTime","education","school","college","major","flp","tel","qq","guardianTel" ,"politicsStatus","nativePlace","talk_record","exam_record"};
		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		PageVM<StudentExtend> pageVm = studentService.pageQuery(page, pageSize,realname,clazzId,status,channelIds,stuTypes,year);

		// 日期处理函数
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");

		for (StudentExtend u : pageVm.getList()) {
			Map<String, Object> map = new HashMap<>();
			map.put("schoolStuClazz", u.getSchoolStuClazz());
			map.put("schoolStuNo", u.getSchoolStuNo());
			map.put("realname", u.getRealname());
			map.put("ddTel", u.getDdTel());
			map.put("gender", u.getGender());
			map.put("nation",u.getNation());
			map.put("idCard", u.getIdCard());
			// 出生日期
			String birth = "";
			try {
				birth = formatter.format(u.getBirth());
			} catch(Exception e) {
				birth = u.getBirth()+"";
			}
			map.put("birth", birth);
			map.put("address", u.getHomeAddress());
			// 毕业时间
			String  graduationTime ="";
			try	{
				graduationTime = formatter.format(u.getGraduationTime());
			} catch (Exception e){
				graduationTime = u.getGraduationTime()+"";
			}
			map.put("graduationTime",graduationTime);
			// 毕业院校
			if(u.getChannel()!=null) {
				// 学院
				map.put("college", u.getChannel().getName());
				if(u.getChannel().getParent()!=null) {
					// 学校
					map.put("school", u.getChannel().getParent().getName());
				}
			}
			map.put("education", u.getEducation());
			map.put("major", u.getMajor());
			map.put("flp", u.getFlp());
			map.put("tel", u.getTel());
			map.put("qq", u.getQq());
			map.put("guardianTel",u.getGuardianTel());
			map.put("politicsStatus", u.getPoliticsStatus());
			map.put("nativePlace", u.getNativePlace());
			// 谈话记录
			String talkRecord = "";
			List<EmployeeEvent>  es = u.getEmployeeEvents();
			if(es.size()>0){
				for(EmployeeEvent e :es){
					talkRecord += e.getContent()+";    ";

				}
			}
			map.put("talk_record",talkRecord);

			// 考试记录
			String examRecord = "";
			List<StudentExamExtend> ees = u.getStudentExamExtends();
			if(ees.size()>0){
				for(StudentExamExtend ee : ees){
					if(ee.getExamInfo()!=null){
						examRecord += ee.getExamInfo().getName() + ":"+ee.getScore() +";    ";
					}
				}
			}
			map.put("exam_record",examRecord);

			dataList.add(map);
		}
		// 2.4 导出文件名
		String excelName = "student_list";
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

	}

	public void inputStreamToFile(java.io.InputStream ins, File file) {
		try {
			java.io.OutputStream os = new java.io.FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	@ApiOperation(value = "批量导入旧数据", notes = "杰普班级、学校、学院")
	@PostMapping("uploadOldStudent")
	public Message uploadOldStudent(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<Student> students = new ArrayList<>();
		for (List<Object> props : list) {
			Student student = new Student();
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				System.out.println(prop);
				switch (i) {
				case 0:	// 学校班级
					student.setSchoolStuClazz((String)prop);
					break;
				case 1:	// 学校学号
					student.setSchoolStuNo((String)prop);
					break;
				case 2: // 学生姓名
					student.setRealname((String)prop);
					break;
				case 3: // 钉钉手机号
					student.setDdTel(prop+"");
					break;
				case 4: // 性别
					String gender = prop+"";
					String[] genders = new String[] {"男","女"};
					boolean flag = Arrays.asList(genders).contains(gender);
					if(!flag) {
						throw new CustomerException("性别录入错误：只允许录入【男 | 女】");
					}
					student.setGender(gender);
					break;
				case 5: // 身份证号
					if(!RegExpValidation.checkIdCard(prop+"")) {
						throw new CustomerException("身份证号错误【"+prop+"】");
					}
					// 设置身份证号
					student.setIdCard(prop+"");
					String birth = IDCardUtil.getBirAgeSex(student.getIdCard()).get("birthday");
					// 设置出生日期
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date date = simpleDateFormat.parse(birth);
						long ts = date.getTime();
						student.setBirth(ts);
					} catch (Exception e) {
						// 生日为当前时间
						student.setBirth(new Date().getTime());
					}

					break;
				case 6: // 家庭住址
					student.setHomeAddress(prop+"");
					break;
				case 7: // 毕业时间
					SimpleDateFormat graduation_time_date_sdf = new SimpleDateFormat("yyyy-MM-dd");
			        Date graduation_time_date = graduation_time_date_sdf.parse(prop+"");
					student.setGraduationTime(graduation_time_date.getTime());
					break;
				case 8: // 学历
					String education = prop+"";
					String[] educations = new String[] {"专科","本科","研究生","其他"};
					boolean education_flag = Arrays.asList(educations).contains(education);
					if(!education_flag) {
						throw new CustomerException("学历录入错误：只允许录入【专科 | 本科 | 研究生 | 其他】");
					}
					student.setEducation(education);
					break;
				case 9: // 专业
					student.setMajor(prop+"");
					break;
				case 10: // 英语水平
					String flp = prop+"";
					String[] flps = new String[] {"CET-4","CET-6","CET-8","无"};
					boolean flp_flag = Arrays.asList(flps).contains(flp);
					if(!flp_flag) {
						throw new CustomerException("外语水平录入错误：只允许录入【CET-4 | CET-6 | CET-8 | 无】");
					}
					student.setFlp(flp);
					break;
				case 11: // 手机号
					String telephone = prop+"";
					if(!RegExpValidation.checkMobile(telephone)) {
						throw new CustomerException("手机号格式错误【"+telephone+"】");
					}
					student.setTel(telephone);
					break;
				case 12: // qq号
					student.setQq(prop+"");
					break;
				case 13: // 监护人手机号
					String guardianTel = prop+"";
//					if(!RegExpValidation.checkMobile(guardianTel)) {
//						throw new CustomerException("手机号格式错误【"+guardianTel+"】");
//					}
					student.setGuardianTel(guardianTel);
					break;
				case 14: // 政治面貌
					student.setPoliticsStatus(prop+"");
					break;
				case 15: // 籍贯
					student.setNativePlace(prop+"");
					break;
				case 16:	//	杰普班级
					student.setClazz(prop+"");
					break;
				case 17:	//	毕业学校
					student.setSchool(prop+"");
					break;
				case 18:	//	毕业学院
					student.setCollege(prop+"");
					break;
				default:
					break;
				}
			}
			students.add(student);
		}
		// 调用业务逻辑层代码完成批量保存操作
		studentService.batchInsertOldStudent(students);
		return MessageUtil.success("导入成功");
	}

	@ApiOperation(value = "批量导入班级学生信息", notes = "杰普班级编号、学校、学院")
	@PostMapping("uploadClazzStudent")
	public Message uploadClazzStudent(@RequestParam("file") MultipartFile file, HttpServletRequest req,Long clazzId) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<Student> students = new ArrayList<>();
		for (List<Object> props : list) {
			Student student = new Student();
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				System.out.println(prop);
				switch (i) {
					case 0:	// 学校班级
						student.setSchoolStuClazz((String)prop);
						break;
					case 1:	// 学校学号
						student.setSchoolStuNo((String)prop);
						break;
					case 2: // 学生姓名
						student.setRealname((String)prop);
						break;
					case 3: // 钉钉手机号
						student.setDdTel(prop+"");
						break;
					case 4: // 性别
						String gender = prop+"";
						String[] genders = new String[] {"男","女"};
						boolean flag = Arrays.asList(genders).contains(gender);
						if(!flag) {
							throw new CustomerException("性别录入错误：只允许录入【男 | 女】");
						}
						student.setGender(gender);
						break;
					case 5: // 身份证号
						if(!RegExpValidation.checkIdCard(prop+"")) {
							throw new CustomerException("身份证号错误【"+prop+"】");
						}
						// 设置身份证号
						student.setIdCard(prop+"");
						String birth = IDCardUtil.getBirAgeSex(student.getIdCard()).get("birthday");
						// 设置出生日期
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
						try {
							Date date = simpleDateFormat.parse(birth);
							long ts = date.getTime();
							student.setBirth(ts);
						} catch (Exception e) {
							// 生日为当前时间
							student.setBirth(new Date().getTime());
						}

						break;
					case 6: // 家庭住址
						student.setHomeAddress(prop+"");
						break;
					case 7: // 毕业时间
                        System.out.println("毕业时间：" + prop);
						SimpleDateFormat graduation_time_date_sdf = new SimpleDateFormat("yyyy-MM-dd");
						Date graduation_time_date = graduation_time_date_sdf.parse(prop+"");
						student.setGraduationTime(graduation_time_date.getTime());
						break;
					case 8: // 学历
						String education = prop+"";
						String[] educations = new String[] {"专科","本科","研究生","其他"};
						boolean education_flag = Arrays.asList(educations).contains(education);
						if(!education_flag) {
							throw new CustomerException("学历录入错误：只允许录入【专科 | 本科 | 研究生 | 其他】");
						}
						student.setEducation(education);
						break;
					case 9: // 专业
						student.setMajor(prop+"");
						break;
					case 10: // 英语水平
						String flp = prop+"";
						String[] flps = new String[] {"CET-4","CET-6","CET-8","无"};
						boolean flp_flag = Arrays.asList(flps).contains(flp);
						if(!flp_flag) {
							throw new CustomerException("外语水平录入错误：只允许录入【CET-4 | CET-6 | CET-8 | 无】");
						}
						student.setFlp(flp);
						break;
					case 11: // 手机号
						String telephone = prop+"";
						if(!RegExpValidation.checkMobile(telephone)) {
							throw new CustomerException("手机号格式错误【"+telephone+"】");
						}
						student.setTel(telephone);
						break;
					case 12: // qq号
						student.setQq(prop+"");
						break;
					case 13: // 监护人手机号
						String guardianTel = prop+"";
//					if(!RegExpValidation.checkMobile(guardianTel)) {
//						throw new CustomerException("手机号格式错误【"+guardianTel+"】");
//					}
						student.setGuardianTel(guardianTel);
						break;
					case 14: // 政治面貌
						student.setPoliticsStatus(prop+"");
						break;
					case 15: // 籍贯
						student.setNativePlace(prop+"");
						break;
					case 16:	//	毕业学校
                        System.out.println("毕业学校：" + prop);
						student.setSchool(prop+"");
						break;
					case 17:	//	毕业学院
                        System.out.println("毕业学院：" + prop);
						student.setCollege(prop+"");
						break;
					default:
						break;
				}
			}
			student.setClazzId(clazzId);
			students.add(student);
		}
		// 调用业务逻辑层代码完成批量保存操作
		studentService.batchInsertClazzStudent(students);
		return MessageUtil.success("导入成功");
	}
}
